package com.markyao.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.markyao.dao.mapper.CommentMapper;
import com.markyao.dao.pojo.Article;
import com.markyao.dao.pojo.Comment;
import com.markyao.dao.pojo.SysUser;
import com.markyao.service.*;
import com.markyao.vo.*;
import com.markyao.vo.parmas.CommentParmas;
import com.markyao.vo.parmas.PageParmas;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    SysUserService sysUserService;
    @Override
    public Result findCommentByAid(Long id) {
        /*
        1.通过文章id获取评论列表
        2.获取文章作者信息
        3.获取文章评论
         */
        List<Comment>commentList= commentMapper.findCommentList(id);
        return Result.success(copyForList(commentList));
    }
    @Autowired
    LoginService loginService;
    @Autowired
    ThreadService threadService;
    @Autowired
    ArticleService articleService;
    @Override
    public Result createComment(CommentParmas commentParmas, String token) {
        /*
        通过线程池获取用户信息
        发布评论
        设计成游客也可以评论
        增加一个判断逻辑，若是没有在线程池获取到用户就自动分配一个
         */
        //验证当前是否已经登录
        SysUser sysUser = loginService.checkT(token);
        Long articleId = commentParmas.getArticleId();
        Comment comment=new Comment();
        comment.setArticleId(articleId);
        if(sysUser!=null){
            //这是有登录的情况
            System.out.println("有登录的时候正常评论....");
            comment.setAuthorId(sysUser.getId());
        }
        else {
            System.out.println("没登陆时评论....");
            comment.setAuthorId(666666L);
        }
        comment.setContent(commentParmas.getContent());
        comment.setCreateDate(System.currentTimeMillis());
        Long parent = commentParmas.getParent();
        Long toUserId = commentParmas.getToUserId();
        if(parent ==null ||parent==0){
            comment.setLevel(1);
            toUserId=articleService.findUidByAid(articleId);//第一层，对象直接设置为文章的作者
        }else {
            comment.setLevel(2);
        }
        comment.setParentId(parent ==null ? 0 : parent);
        comment.setToUid(toUserId ==null ? 0 : toUserId);
        Integer counts = this.commentMapper.findCommentCountsByAid(articleId);
        this.commentMapper.insert(comment);
        //发布评论成功需要实时增加评论数
        //采用跟更新阅读数一样的异步
        threadService.updateCommentCounts(this.commentMapper,commentParmas.getArticleId(),counts);
        return Result.success(null);
    }

    @Override
    public Result deleteByCId(List<Long> idList) {
        System.out.println("-----------------------ids"+idList.size());
        System.out.println("-----------------------ids");
        System.out.println("-----------------------ids");
        for (Long id : idList) {
            System.out.println(id);
        }
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        commentMapper.deleteByCid(idList);

        return Result.success(null);
    }

    @Override
    public Result getAllComments(PageParmas pageParams, String token) {
        SysUser sysUser = loginService.checkT(token);
        if(sysUser==null){
            //没登陆
            return Result.failed(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.NO_LOGIN.getMsg());
        }

        PageHelper.startPage(pageParams.getPage(), pageParams.getPageSize());
//        List<Comment>commentList=commentMapper.findAll();
        List<Comment>commentList=commentMapper.findAllByUid(sysUser.getId());
        PageInfo pageInfo=new PageInfo(commentList);
        List<CommentVo> commentVoList=copyForList(commentList);
        long total = pageInfo.getTotal();
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setList(commentVoList);
        pageResult.setSuccess(true);
        return Result.success(pageResult);
    }


    private List<CommentVo> copyForList(List<Comment> commentList) {
        List<CommentVo> commentVos=new ArrayList<>();
        for (Comment comment : commentList) {
            commentVos.add(copy(comment));
        }
        return commentVos;
    }

    private CommentVo copy(Comment comment) {
        CommentVo commentVo=new CommentVo();
        Long articleId = comment.getArticleId();
        String aTitle=articleService.findTitleById(articleId);
        ArticleVo article = new ArticleVo();
        article.setTitle(aTitle);
        article.setId(String.valueOf(articleId));
        commentVo.setArticle(article);
        BeanUtils.copyProperties(comment,commentVo);
        commentVo.setId(String.valueOf(comment.getId()));
        //在这里处理一下时间
        Long dateTime = comment.getCreateDate();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date(dateTime);
        String createDate = sdf.format(date);
        commentVo.setCreateDate(createDate);
        //通过AuthorId获取评论的作者信息
        commentVo.setAuthor(sysUserService.findUserVoById(comment.getAuthorId()));
        //获取子评论列表
        Integer level = comment.getLevel();
        /*
        逻辑：
        如果是一层评论，则会有子列表
        如果不是一层评论,则会有toUser对象
         */
        if(1 == level){
            //查找子评论列表
            Long id = comment.getId();
            List<CommentVo> commentVos= findCommnetsByParentId(id);
            commentVo.setChildrens(commentVos);
            UserVo toUserVo = sysUserService.findUserVoById(articleService.findUidByAid(articleId));
            commentVo.setToUser(toUserVo);
        }
        //获取toUser 给谁评论
        if(level > 1){
            Long toUid = comment.getToUid();
            UserVo toUserVo = sysUserService.findUserVoById(toUid);
            commentVo.setToUser(toUserVo);
        }
        return commentVo;
    }

    private List<CommentVo> findCommnetsByParentId(Long id) {
        List<Comment> commentList=commentMapper.findCommentsChild(id);
        return copyForList(commentList);
    }
}
